﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nature
{
    class M1KgUtil
    {
        ModelObject m_context;
        double[] m_concentrations;

        public M1KgUtil(ModelObject context)
        {
            m_context = context;
            m_concentrations = new double[context.Nsp];
        }

        public double MixtureAveragedMolarMass(ReadOnlyArray<double> x, bool normalized = false)
        {
            var w = m_context.SpeciesMolarMasses;
            double mass = 0.0;
            double xsum = 0.0;
            double xcur;
            for (int isp = 0; isp < m_context.Nsp; ++isp)
            {
                xcur = x[isp];
                xsum += xcur;
                mass += xcur * w[isp];
            }
            return normalized ? mass / xsum : mass;
        }

        public void ComputeElementMolesPerMass(double[] n, ReadOnlyArray<double> x)
        {
            var spel = m_context.SpelMatrix;
            double nsum = 0.0;
            double csum = 1.0 / MixtureAveragedMolarMass(x, false);
            for (int isp = 0; isp < m_context.Nsp; ++isp)
            {
                m_concentrations[isp] = x[isp] * csum;
            }
            for (int iel = 0; iel < m_context.Nel; ++iel)
            {
                n[iel] = 0.0;
                for (int isp = 0; isp < m_context.Nsp; ++isp)
                {
                    n[iel] += m_concentrations[isp] * spel[isp][iel];
                }
                nsum += n[iel];
            }
        }
    }
}
